<template>
  <view class="page-container">
    <view class="content">
      <!-- 用户信息卡片 -->
      <view class="user-card">
        <template v-if="storeIsLogin">
          <view class="user-header">
            <!-- 使用button包装头像，支持微信头像选择 -->
            <button 
              class="avatar-wrapper"
              open-type="chooseAvatar" 
              @chooseavatar="onChooseAvatar"
            >
              <image :src="avatarUrl" class="avatar" mode="aspectFill"></image>
            </button>
            <view class="user-details">
              <view class="username">{{ userInfo.nickName || '未设置昵称' }}</view>
              <view class="user-id">ID: {{ userInfo.userId || '' }}</view>
            </view>
            <view class="edit-profile" @click="editProfile">
              <text>编辑资料</text>
            </view>
          </view>
          
          <!-- 用户统计数据 -->
          <view class="user-stats">
            <view class="stat-item">
              <text class="stat-num">{{ userStats.albums || 0 }}</text>
              <text class="stat-label">相册</text>
            </view>
            <view class="stat-item">
              <text class="stat-num">{{ userStats.photos || 0 }}</text>
              <text class="stat-label">照片</text>
            </view>
            <view class="stat-item">
              <text class="stat-num">{{ userStats.likes || 0 }}</text>
              <text class="stat-label">获赞</text>
            </view>
          </view>
        </template>
        <template v-else>
          <view class="login-prompt">
            <image src="/static/images/default-avatar.png" class="avatar" mode="aspectFill"></image>
            <text class="login-text">登录以使用更多功能</text>
            <button class="login-btn" @click="goLogin">去登录</button>
          </view>
        </template>
      </view>
      
      <!-- 快捷功能区 -->
      <view class="quick-actions">
        <view class="action-item" @click="createAlbum">
          <view class="action-icon">📁</view>
          <text>创建相册</text>
        </view>
        <view class="action-item" @click="uploadPhotos">
          <view class="action-icon">📷</view>
          <text>上传照片</text>
        </view>
        <view class="action-item" @click="sharePhotos">
          <view class="action-icon">🔗</view>
          <text>分享相册</text>
        </view>
      </view>

      <!-- 菜单列表 -->
      <view class="menu-list">
        <view class="menu-group-title">我的内容</view>
        <!-- 我的相册 -->
        <view class="menu-item" @click="navigateTo('/pages/album/list')">
          <view class="menu-icon">📸</view>
          <view class="menu-text">我的相册</view>
          <view class="menu-arrow">
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
        
        <!-- 我的收藏 -->
        <view class="menu-item" @click="navigateTo('/pages/favorites/list')">
          <view class="menu-icon">⭐</view>
          <view class="menu-text">我的收藏</view>
          <view class="menu-arrow">
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
        
        <view class="menu-group-title">设置与服务</view>
        <!-- 设置 -->
        <view class="menu-item" @click="navigateTo('/pages/settings/index')">
          <view class="menu-icon">⚙️</view>
          <view class="menu-text">设置</view>
          <view class="menu-arrow">
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
        
        <!-- 消息通知 -->
        <view class="menu-item" @click="navigateTo('/pages/my/notifications')">
          <view class="menu-icon">🔔</view>
          <view class="menu-text">消息通知</view>
          <view class="menu-badge unread" v-if="notificationCount > 0">{{notificationCount}}</view>
          <view class="menu-arrow">
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
        
        <!-- 联系客服 -->
        <view class="menu-item" @click="contactService">
          <view class="menu-icon">📞</view>
          <view class="menu-text">联系客服</view>
          <view class="menu-arrow">
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
        
        <!-- 关于我们 -->
        <view class="menu-item" @click="showAbout">
          <view class="menu-icon">ℹ️</view>
          <view class="menu-text">关于我们</view>
          <view class="menu-arrow">
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
      </view>
      
      <!-- 退出登录按钮 -->
      <view class="logout-btn" v-if="storeIsLogin" @click="logout">退出登录</view>
    </view>
    
    <tab-bar :tabIndex="2"></tab-bar>
  </view>
</template>

<script>
import TabBar from '@/components/tab-bar/tab-bar.vue';
import { mockData } from '@/mock/index.js';
import { getUserInfo, uploadAvatar, getUserSummary } from '@/api/user';
import { checkLogin } from '@/utils/auth';
import { getAvatarUrl } from '@/utils/image.js';

export default {
  components: {
    TabBar
  },
  data() {
    return {
      userInfo: {},
      isLogin: false,
      avatarUrl: '/static/default-avatar.png',
      userStats: {
        albums: 0,
        photos: 0,
        likes: 0
      },
      notificationCount: 0
    }
  },
  computed: {
    storeUserInfo() {
      return this.$store.state.userInfo;
    },
    storeIsLogin() {
      return this.$store.state.isLogin;
    }
  },
  onLoad() {
    this.getUserInfo();
  },
  onShow() {
    console.log('我的页面显示');
    this.getUserInfo();
  },
  methods: {
    async getUserInfo() {
      console.log('获取用户信息, 登录状态:', this.storeIsLogin);
      this.isLogin = this.storeIsLogin;
      
      if (this.isLogin) {
        try {
          const userInfo = this.storeUserInfo;
          if (userInfo) {
            console.log('从store获取到用户信息:', userInfo);
            this.userInfo = userInfo;
            
            // 获取用户摘要信息（包含统计数据）
            this.fetchUserSummary();
            
            // 设置头像URL
            if (userInfo.avatar) {
              console.log('处理头像URL:', userInfo.avatar);
              this.avatarUrl = getAvatarUrl(userInfo.avatar);
            } else {
              this.avatarUrl = '/static/images/default-avatar.png';
            }
            
            if (userInfo.unreadMsgCount) {
              const notificationMenu = this.menuData.find(item => item.id === 'notifications');
              if (notificationMenu) {
                notificationMenu.badge = userInfo.unreadMsgCount;
              }
            }
          } else {
            console.log('store中无用户信息，从API获取');
            await this.$store.dispatch('fetchUserInfo');
            const freshUserInfo = this.$store.state.userInfo;
            if (freshUserInfo) {
              this.userInfo = freshUserInfo;
              
              // 获取用户摘要信息（包含统计数据）
              this.fetchUserSummary();
              
              // 处理头像URL
              this.avatarUrl = getAvatarUrl(freshUserInfo.avatar) || '/static/images/default-avatar.png';
            }
          }
        } catch (error) {
          console.error('获取用户信息失败:', error);
          // 显示错误提示
          uni.showToast({
            title: '获取用户信息失败',
            icon: 'none'
          });
        }
      } else {
        console.log('用户未登录');
        // 清空用户信息
        this.userInfo = {};
        this.userStats = { albums: 0, photos: 0, likes: 0 };
        this.avatarUrl = '/static/avatar-default.png';
      }
    },
    editProfile() {
      uni.navigateTo({
        url: '/pages/my/edit-profile?stay=true'
      });
    },
    logout() {
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            this.$store.dispatch('clearAuth');
            uni.showToast({
              title: '已退出登录',
              icon: 'success'
            });
            // 更新登录状态
            this.isLogin = false;
            // 重置数据
            this.userInfo = {};
            this.userStats = { albums: 0, photos: 0, likes: 0 };
            this.avatarUrl = '/static/avatar-default.png';
          }
        }
      });
    },
    createAlbum() {
      if (!this.isLogin) {
        this.goLogin();
        return;
      }
      uni.navigateTo({ 
        url: '/pages/album/create'
      });
    },
    uploadPhotos() {
      if (!this.isLogin) {
        this.goLogin();
        return;
      }
      uni.navigateTo({ 
        url: '/pages/photo/upload'
      });
    },
    sharePhotos() {
      if (!this.isLogin) {
        this.goLogin();
        return;
      }
      uni.navigateTo({ 
        url: '/pages/share/create'
      });
    },
    goLogin() {
      uni.navigateTo({
        url: '/pages/login/login'
      });
    },
    navigateTo(url) {
      if (!this.isLogin) {
        this.goLogin();
        return;
      }
      
      uni.navigateTo({
        url: url
      });
    },
    contactService() {
      uni.navigateTo({
        url: '/pages/my/contact'
      });
    },
    showAbout() {
      uni.navigateTo({
        url: '/pages/my/about'
      });
    },
    // 上传/更换头像
    onChooseAvatar(e) {
      if (!this.isLogin) {
        uni.navigateTo({
          url: '/pages/login/login'
        });
        return;
      }
      
      console.log('选择头像事件:', e);
      // 获取微信临时头像URL
      const { avatarUrl } = e.detail;
      if (avatarUrl) {
        // 先更新本地展示
        this.avatarUrl = avatarUrl;
        
        // 上传头像到服务器
        this.uploadAvatar(avatarUrl);
      }
    },
    // 上传头像到服务器
    async uploadAvatar(filePath) {
      uni.showLoading({
        title: '上传中...'
      });
      
      try {
        // 调用上传头像API
        const result = await uploadAvatar(filePath);
        
        if (result && result.code === 0) {
          // 更新store中的用户信息
          const updatedUserInfo = {...this.storeUserInfo, avatar: result.data.avatarUrl};
          this.$store.commit('SET_USER_INFO', updatedUserInfo);
          
          uni.showToast({
            title: '头像更新成功',
            icon: 'success'
          });
        } else {
          throw new Error(result.message || '上传失败');
        }
      } catch (error) {
        console.error('上传头像失败:', error);
        uni.showToast({
          title: '上传头像失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    async fetchUserSummary() {
      try {
        console.log('获取用户摘要信息...');
        const result = await getUserSummary();
        console.log('用户摘要信息:', result);
        
        if (result && result.data) {
          // 更新用户统计数据
          this.userStats = {
            albums: result.data.albumCount || 0,
            photos: result.data.photoCount || 0,
            likes: result.data.likeCount || 0
          };
          
          // 更新通知计数
          this.notificationCount = result.data.unreadMsgCount || 0;
        }
      } catch (error) {
        console.error('获取用户摘要信息失败:', error);
      }
    },
    async uploadNewAvatar() {
      // Implementation of uploadNewAvatar method
    }
  }
};
</script>

<style>
.page-container {
  padding-bottom: 0; /* 移除底部内边距 */
  position: relative;
  min-height: 100vh;
}

.content {
  padding: 30rpx;
  padding-bottom: 180rpx; /* 从150rpx增加到180rpx，为TabBar预留更多空间 */
}

/* 用户卡片样式 */
.user-card {
  background-color: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.user-header {
  display: flex;
  align-items: center;
  position: relative;
}

.avatar-container {
  position: relative;
  margin-right: 20rpx;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background-color: #f0f0f0;
  border: 2rpx solid #f5f5f5;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.user-details {
  flex: 1;
}

.username {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.user-id {
  font-size: 24rpx;
  color: #999;
}

.edit-profile {
  position: absolute;
  right: 0;
  top: 10rpx;
  background-color: #f0f8f0;
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
  font-size: 24rpx;
  color: #3a8838;
}

/* 用户统计数据 */
.user-stats {
  display: flex;
  justify-content: space-around;
  margin-top: 40rpx;
  border-top: 1px solid #f0f0f0;
  padding-top: 30rpx;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-num {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #999;
}

/* 快捷功能区 */
.quick-actions {
  display: flex;
  justify-content: space-between;
  background-color: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 33.33%;
}

.action-icon {
  font-size: 40rpx;
  margin-bottom: 10rpx;
}

.action-item text {
  font-size: 24rpx;
  color: #666;
}

/* 菜单列表样式 */
.menu-list {
  background-color: #fff;
  border-radius: 15rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 30rpx;
}

.menu-group-title {
  font-size: 26rpx;
  color: #999;
  padding: 20rpx 30rpx;
  background-color: #f8f8f8;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1px solid #f5f5f5;
  position: relative;
}

.menu-item:active {
  background-color: #f9f9f9;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-icon {
  font-size: 32rpx;
  margin-right: 20rpx;
  width: 40rpx;
  text-align: center;
}

.album-icon, .memory-icon {
  color: #3a8838;
}

.favorite-icon {
  color: #ff5a5f;
}

.settings-icon, .about-icon {
  color: #666;
}

.notification-icon {
  color: #ff9500;
}

.service-icon {
  color: #007aff;
}

.menu-text {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.menu-right {
  display: flex;
  align-items: center;
}

.menu-badge {
  font-size: 24rpx;
  color: #999;
  margin-right: 10rpx;
}

.menu-badge.new {
  color: #fff;
  background-color: #3a8838;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  font-size: 20rpx;
}

.menu-badge.unread {
  color: #fff;
  background-color: #ff5a5f;
  height: 36rpx;
  min-width: 36rpx;
  border-radius: 18rpx;
  text-align: center;
  line-height: 36rpx;
  margin-right: 10rpx;
  font-size: 22rpx;
}

.menu-arrow {
  color: #ccc;
  font-size: 28rpx;
}

/* 退出登录按钮 */
.logout-btn {
  margin: 40rpx 0 40rpx; /* 增加底部margin到40rpx */
  text-align: center;
  padding: 25rpx 0;
  background-color: #fff;
  border-radius: 10rpx;
  color: #ff5a5f;
  font-size: 28rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

/* 登录提示样式 */
.login-prompt {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 0;
}

.login-prompt .avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  margin-bottom: 20rpx;
}

.login-text {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
}

.login-btn {
  background: #3a8838;
  color: #fff;
  font-size: 28rpx;
  padding: 10rpx 60rpx;
  border-radius: 40rpx;
  border: none;
}

.login-btn::after {
  border: none;
}

/* 微信头像选择按钮样式 */
.avatar-wrapper {
  padding: 0;
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  margin-right: 30rpx;
  line-height: 1;
  background-color: transparent;
}

.avatar-wrapper::after {
  border: none;
}

.avatar-wrapper .avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  border: 4rpx solid #3a8838;
}
</style> 